using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace Sedge.UI.Component
{
	public class SimplePanel : Panel
	{
		private List<GraphicsPath> _pathList = new List<GraphicsPath>();
		private GraphicsPath _mousePath = new GraphicsPath();
		private int _x = -1;
		private int _y = -1;

		public Bitmap Bitmap { get; set; }

		protected override void WndProc(ref Message messg)
		{
			// turn the erase background message into a null message
			if ((int)0x0014 == messg.Msg) //if message is is erase background
			{
				messg.Msg = (int)0x0000; //reset message to null
			}
			base.WndProc(ref messg);
		}

		protected override void OnMouseDown(MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Left)
			{
				_mousePath.StartFigure();
				_x = e.X;
				_y = e.Y;
			}
		}

		protected override void OnMouseMove(MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Left)
			{
				_mousePath.AddLine(_x, _y, e.X, e.Y);
				_x = e.X;
				_y = e.Y;
				Invalidate();
			}
		}

		protected override void OnMouseUp(MouseEventArgs e)
		{
			_pathList.Add(_mousePath);
			_mousePath = new GraphicsPath();
			Invalidate();
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			Bitmap bmp = new Bitmap(Width, Height);
			Graphics g = Graphics.FromImage(bmp);
			g.FillRectangle(Brushes.White, 0, 0, Width, Height);
			
			if (Bitmap != null)
			{
				g.DrawImage(Bitmap, 0, 0);
			}

			Pen drawingPen = new Pen(Color.Green, 5);
			foreach (GraphicsPath graphicsPath in _pathList)
			{
				g.DrawPath(drawingPen, graphicsPath);
			}
			g.DrawPath(drawingPen, _mousePath);

			e.Graphics.DrawImage(bmp, 0,0);
		}
	}
}